package com.fzd.code.common;

import lombok.Data;

import java.util.HashMap;

@Data
public class Result {
	private String status;
	private String msg;
	private Object data;

	public Result(){}

	public Result(String status){
		this.setStatus(status);
	}
	public Result(String status, String msg){
		this.setStatus(status);
		this.setMsg(msg);
	}
	public Result(String status, String msg, Object data){
		this.setStatus(status);
		this.setMsg(msg);
		this.setData(data);
	}

	public static Result OK(){
		return new Result("OK","OK",null);
	}
	public static Result OK(String message){
		return new Result("OK",message,null);
	}
	public static Result OK(String message, Object data){
		return new Result("OK",message,data);
	}
	public static Result OK(Object data){
		return new Result("OK","OK",data);
	}

	public static Result OK(boolean isOK){
		return new Result(
				isOK?"OK":"ERROR",
				isOK?"OK":"ERROR",
				null
		);
	}

	public static Result ERROR(){
		return new Result("ERROR","ERROR");
	}
	public static Result ERROR(String message){
		return new Result("ERROR",message);
	}
	public static Result ERROR(String message,Object data){
		return new Result("ERROR",message,data);
	}

	public static Result ERROR(Object data){
		return new Result("ERROR","ERROR",data);
	}

	public static Result databaseUpdate(Integer databaseUpdateResult){
		return databaseUpdateResult!=null&&databaseUpdateResult>0? Result.OK(): Result.ERROR();
	}
	public static void databaseUpdateThrow(Integer databaseUpdateResult) throws  Exception{
		if(databaseUpdateResult==null || databaseUpdateResult<1) throw new Exception("ERROR");
	}
	public static void databaseUpdateNullThrow(Integer databaseUpdateResult) throws  Exception{
		if(databaseUpdateResult==null) throw new Exception("ERROR");
	}
	public static void databaseUpdateNullThrow(Integer databaseUpdateResult,String errorMsg) throws  Exception{
		if(databaseUpdateResult==null) throw new Exception(errorMsg==null?"ERROR":errorMsg);
	}

	public static Result failedThrow(Result result){
		if(!result.getStatus().equals("OK")){
			throw new RuntimeException(result.msg);
		}
		return result;
	}

	public static void failedThrow(boolean result,String message) throws Exception{
		if(!result) throw new Exception(message==null?"操作失败":message);
	}

	public Result data(String key,Object data){
		((HashMap)this.data).put(key,data);
		return this;
	}
}
